
var socket = '', // websocket缓存
    userId = '', // 当前用户id    
    msgList = {}, // 缓存私聊历史消息
    interval = '', // 当聊天窗口不是用户当前显示窗口缓存title闪烁的setInterval
    flag = false, // 用于title闪烁切换
    currPrivate = '', // 当前私聊人的ID
    newImage = null; // 当前消息的图片
    pMsgListHeight = ''; // 缓存私聊框高度
    title = document.title; // 缓存当前title，用于闪烁效果
var CHAT = {
    // 获取用户id
    getUid: function () {
        return new Date().getTime() + '' + Math.floor(Math.random() * 899 + 100);
    },

    // title闪烁效果
    flag_title: function () {
        if (!flag) {
            flag = true;
            document.title = title + '【您有新消息】';
        } else {
            flag = false;
            document.title = title;
        }
    },

    /**
     * 切换到好友聊天框
     * @param id 好友id
     * @param userName 好友名字
     */
    click_user: function (id, userName) {
        if (!$('.private_msg').hasClass('show')) {
            $('.private_msg').addClass('show');
        }

        // 判断点击的好友不是当前私聊的好友
        currPrivate != id && (
            currPrivate = id,
            $('#pm').focus(),
            $('#private_name').text(userName),
            $('#psend').attr('onclick', 'CHAT.submit(' + id + ');'),
            $('#pupload').attr('onchange', 'CHAT.getBse64Image(this, ' + id + ');'),
            $('[data-id="' + id + '"]').find('span').length && $('[data-id="' + id + '"]').find('span').remove(),
            msgList[id] ? ($('#pmessages').html(msgList[id]).append('<div class="msg_system">以上为历史消息</div>'), 
                            // 折中解决历史消息渲染聊天框不会移动到最底部
                            (function(){
                                var Inter = setInterval(function(){
                                    if(pMsgListHeight != $('#pmessages').height()){
                                        pMsgListHeight = $('#pmessages').height();
                                    }else{
                                        CHAT.scrollToBottom('#pmessages');
                                        pMsgListHeight = '';
                                        clearInterval(Inter);
                                        Inter = null;
                                    }
                                }, 200)})()): $('#pmessages').html('')            
        );
    },

    /**
     * 加载表情插件
     * @param el 选中表情插入的input或可编辑的div
     * @param btn 点击弹出表情框的元素按钮
     */
    load_emoji: function(el, btn){
        $(el).emoji({
            button: btn,
            showTab: false,
            animation: 'slide',
            icons: [{
                name: "贴吧表情",
                path: "/img/tieba/",
                maxNum: 50,
                file: ".jpg",
                placeholder: ":{alias}:",
                alias: {
                    1: "hehe",
                    2: "haha",
                    3: "tushe",
                    4: "a",
                    5: "ku",
                    6: "lu",
                    7: "kaixin",
                    8: "han",
                    9: "lei",
                    10: "heixian",
                    11: "bishi",
                    12: "bugaoxing",
                    13: "zhenbang",
                    14: "qian",
                    15: "yiwen",
                    16: "yinxian",
                    17: "tu",
                    18: "yi",
                    19: "weiqu",
                    20: "huaxin",
                    21: "hu",
                    22: "xiaonian",
                    23: "neng",
                    24: "taikaixin",
                    25: "huaji",
                    26: "mianqiang",
                    27: "kuanghan",
                    28: "guai",
                    29: "shuijiao",
                    30: "jinku",
                    31: "shengqi",
                    32: "jinya",
                    33: "pen",
                    34: "aixin",
                    35: "xinsui",
                    36: "meigui",
                    37: "liwu",
                    38: "caihong",
                    39: "xxyl",
                    40: "taiyang",
                    41: "qianbi",
                    42: "dnegpao",
                    43: "chabei",
                    44: "dangao",
                    45: "yinyue",
                    46: "haha2",
                    47: "shenli",
                    48: "damuzhi",
                    49: "ruo",
                    50: "OK"
                },
                title: {
                    1: "呵呵",
                    2: "哈哈",
                    3: "吐舌",
                    4: "啊",
                    5: "酷",
                    6: "怒",
                    7: "开心",
                    8: "汗",
                    9: "泪",
                    10: "黑线",
                    11: "鄙视",
                    12: "不高兴",
                    13: "真棒",
                    14: "钱",
                    15: "疑问",
                    16: "阴脸",
                    17: "吐",
                    18: "咦",
                    19: "委屈",
                    20: "花心",
                    21: "呼~",
                    22: "笑脸",
                    23: "冷",
                    24: "太开心",
                    25: "滑稽",
                    26: "勉强",
                    27: "狂汗",
                    28: "乖",
                    29: "睡觉",
                    30: "惊哭",
                    31: "生气",
                    32: "惊讶",
                    33: "喷",
                    34: "爱心",
                    35: "心碎",
                    36: "玫瑰",
                    37: "礼物",
                    38: "彩虹",
                    39: "星星月亮",
                    40: "太阳",
                    41: "钱币",
                    42: "灯泡",
                    43: "茶杯",
                    44: "蛋糕",
                    45: "音乐",
                    46: "haha",
                    47: "胜利",
                    48: "大拇指",
                    49: "弱",
                    50: "OK"
                }
            },{
                name: "QQ表情",
                path: "/img/qq/",
                maxNum: 91,
                excludeNums: [41, 45, 54],
                file: ".gif"
            }]
        });
    },

    // 返回群聊
    return: function () {
        $('.private_msg').removeClass('show');
        $('#pmessages').html('');
        $('.return').find('span').length && $('.return').find('span').remove();
        currPrivate = '';
    },

    /**
     * 登录
     * @param key 进入聊天室的用户昵称
     */
    userNameSubmit: function (key) {
        if (key) {
            $('#userName').val('');
            $('#loginbox').hide();
            $('#chatbox').show();
            this.init(key);
        } else {
            var userName = $('#userName').val();
            if (!!userName) {
                $('#userName').val('');
                $('#loginbox').hide();
                $('#chatbox').show();
                this.init(userName);
            }
        }
        return false;
    },

    /**
     * 滚动条始终在底部
     * @param ele 执行在哪一个聊天消息框
     */
    scrollToBottom: function (ele) {
        console.log($(ele).height());
        $(ele).parent().scrollTop($(ele).height());
        // $(ele).next('.bot_dom')[0].scrollIntoView();
    },

    /**
     * 将图片转换成base64，在进行传输
     * @param img input元素
     * @param id 私聊的好友ID, 群聊为空
     */
    getBse64Image: function(img, id){
        var eleId = $(img).attr('id');
        var imgFile = new FileReader();
        var files = img.files[0];
        if(!/image/g.test(files.type)){
            alert('请选择图片文件！');
            return false;
        }
        imgFile.readAsDataURL(img.files[0]);
        imgFile.onload = function(){
            var imgData = this.result; // base64数据
            $(img).val('');
            CHAT.submitImage(imgData, id);
        }
    },

    /**
     * 发送本地图片
     * @param imgData 图片base64数据
     * @param id 群聊为空，私聊为对方的id
     */
    submitImage: function(imgData, id){
        socket.emit('message', { msg: imgData, userId: userId, privateId: id, img: true });
        return false;
    },

    /**
     * 点击发送按钮，提交输入的信息
     * @param id 群聊为空，私聊为对方的id
     */
    submit: function (id) {
        var el = id ? $('#pm') : $('#m');
        var msg = el.html();
        if (!msg) return false;
        el.html('').focus();
        socket.emit('message', { msg: msg, userId: userId, privateId: id });
        return false;
    },

    /**
     * 系统信息显示
     * @param info 消息详情信息
     * @param action 表明用户是登录h还是退出
     */
    updataSysMsg: function (info, action) {
        var list = '';
        if (info.user.userId != userId) {
            // 添加系统消息
            var html = '';
            html += '<div class="msg_system">';
            html += info.user.userName;
            html += (action == 'login') ? '加入房间' : '退出房间';
            html += '</div>';
        }
        $('#cmessages').append(html);

        // 更新在线人数显示
        $('.counts').text(info.userCounts);

        // 更新在线人数列表
        for (var i in info.userLists) {
            if (userId == i) {
                list = '<li class="userListShow">' + info.userLists[i] + '<span style="color: #f06;">(我)</span></li>' + list;
            } else {
                list += '<li class="userListShow" data-id="' + i + '" onclick="CHAT.click_user(' + i + ', \'' + info.userLists[i] + '\')">' + info.userLists[i] + '</li>';
            }
        }
        $('.allUsers').html(list);

        CHAT.scrollToBottom('#cmessages');
    },

    /**
     * 退出登录
     */
    loginout: function () {
        window.confirm('确定退出房间吗？') && (function () {
            sessionStorage.removeItem('userId');
            sessionStorage.removeItem('userName');
            $('#loginbox').show();
            $('#chatbox').hide();
            // 断开websocket连接
            socket.disconnect();
        })();
    },

    /**
     * 进入房间初始化
     * @param user string或object
     */
    init: function (user) {
        var userName = '';

        // 连接socket
        socket = io();

        //初始化群聊与私聊的表情初始化
        this.load_emoji("#m","#emoji_btn");
        this.load_emoji("#pm","#emoji_btn_p");

        // 当user为string时为新进用户，object时为重新登录，从sessionstorage中取出缓存信息
        if (typeof user === 'string') {
            userId = CHAT.getUid();
            userName = user;

            // 缓存用户信息
            sessionStorage.setItem('userId', userId);
            sessionStorage.setItem('userName', userName);
        } else {
            userId = user.userId;
            userName = user.userName;
        }
        $('.userName').html(userName);

        /**
         * 发送登录请求
         * @param userId 用户ID
         * @param userName 用户名字
         */
        socket.emit('login', { userId: userId, userName: userName });

        /**
         * 接收到用户登录信息
         * @param info 服务器推送的最新用户信息
         */
        socket.on('login', function (info) {
            CHAT.updataSysMsg(info, 'login');
        });

        /**
         * 接收到用户退出信息
         * @param info 服务器推送的最新用户信息
         */
        socket.on('loginout', function (info) {
            CHAT.updataSysMsg(info, 'loginout');
        });

        /**
         * 私聊用户已下线提示
         */
        socket.on('pri_error', function(info){
            $('#pmessages').append('<div class="msg_system" id="offlineTips">对方已下线</div>');
            var timeout = setTimeout(function() {
                $('#pmessages').find('#offlineTips').remove();
                clearTimeout(timeout);
                timeout = null;
            }, 2000);
        });

        /**
         * 接收到chat message时
         * @param obj 
         */
        socket.on('message', function (obj) {
            //将chat message显示在页面
            var html = '';
            if (obj.user == userId) {
                if(obj.img){
                    html = '<li class="me"><div class="msg_name">' + obj.userLists[obj.user] + ' ：</div><p class="msgContent"><img class="msg_img" src="' + obj.msg + '" /></p></li>'
                }else{
                    html = '<li class="me"><div class="msg_name">' + obj.userLists[obj.user] + ' ：</div><p class="msgContent">' + obj.msg + '</p></li>'
                }
            } else {
                if(obj.img){
                    html = '<li class="service"><div class="msg_name">' + obj.userLists[obj.user] + ' ：</div><p class="msgContent"><img class="msg_img" src="' + obj.msg + '" /></p></li>';
                }else{
                    html = '<li class="service"><div class="msg_name">' + obj.userLists[obj.user] + ' ：</div><p class="msgContent">' + obj.msg + '</p></li>';
                }

                //当聊天窗口不是当前用户显示窗口时执行网页标题闪烁
                if (!interval && document.visibilityState != 'visible') {
                    interval = setInterval(CHAT.flag_title, 300);
                }
            }

            // 有obj.privateId则为私聊消息
            if (obj.privateId) {
                //obj.orgin == sender 时则这消息为自己发送
                var cache_id = obj.orgin == 'sender' ? obj.privateId : obj.user;
                $('#pmessages').append(html);

                // 缓存消息
                !msgList[cache_id] && (msgList[cache_id] = []);
                msgList[cache_id].push(html);

                // 当聊天对象在群聊或者私聊用户不是发消息者，则在在线人员列表中的对方名字后添加一个消息提示
                (!$('.private_msg').hasClass('show') || currPrivate != cache_id) && !$('[data-id="' + cache_id + '"]').find('span').length &&
                    $('[data-id="' + cache_id + '"]').append('<span style="font-size: 10px;color: red;"> (new)</span>');
            } else {
                $('#cmessages').append(html);

                //当用户在私聊时，有群聊消息时的消息提示
                $('.private_msg').hasClass('show') && !$('.return').find('span').length  &&
                $('.return').append('<span style="font-size: 10px;color: red;"> (new)</span>');

            }
            
            if(obj.img){
                newImage = new Image();
                newImage.src = obj.msg;
                newImage.onload = function(){
                    CHAT.scrollToBottom(obj.privateId ? '#pmessages' : '#cmessages');
                }
            }else{
                CHAT.scrollToBottom(obj.privateId ? '#pmessages' : '#cmessages');
            }

        });

        /**
         * 切换浏览器窗口监控
         */
        document.addEventListener('visibilitychange', function () {
            if (document.visibilityState == 'visible' && interval) {
                clearInterval(interval);
                interval = '';
                document.title = title;
            }
        });

        /**
         * 绑定回车键消息发送
         */
        $('#m, #pm').on('keydown', function (e) {
            e = e || event;
            if (e.keyCode === 13) {
                CHAT.submit(currPrivate);
            }
        });
    }
}

var key = {};
key.userName = sessionStorage.getItem('userName');
key.userId = sessionStorage.getItem('userId');
if (key.userName && key.userId) {
    CHAT.userNameSubmit(key);
}

/**
 * 绑定回车键登录
 */
$('#userName').on('keydown', function (e) {
    e = e || event;
    if (e.keyCode === 13) {
        CHAT.userNameSubmit();
    }
});

/**
 * 禁止用户手动刷新， 会造成服务器不断断开与连接
 */
$(document).bind("keydown", function (e) {
    e = window.event || e;
    if (e.keyCode == 116) {
        e.keyCode = 0;
        return false;
    }
});